package com.ebupt.migu.restapi;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ebupt.migu.common.pojo.UserRelation;
import com.ebupt.migu.common.request.HeadBean;
import com.ebupt.migu.common.request.Request;
import com.ebupt.migu.common.request.RequestBean;
import com.ebupt.migu.common.response.Response;
import com.ebupt.migu.common.util.*;

import lombok.extern.slf4j.Slf4j;

/**
 * @author tz
 */
@Slf4j
public class RestHttpPost {

    private static PropertiesUtil prop = new PropertiesUtil();
    private static String secretId = prop.getValue("secretId");
    private static String secretKey = prop.getValue("secretKey");

    // 测试环境
    // private static String secretId = "music_test";
    // private static String secretKey = "c523ff4d0ad447848623011eaeec6f0e";

    // 生产环境
    // private static String secretId = "music";
    // private static String secretKey = "df71069bc80046c8afeddf32f7b2e6e7";

    /**
     * 对接标签平台统一http远程调用
     *
     * @param t
     * @param <T>
     */
    public <T> Response<String> doRest(T t, String url) {
        // 构造统一请求报文
        Request<String> request = new Request<>();
        request.setHead(getHeadBean(t));
        RequestBean<String> str = new RequestBean<>();
        str.setParam(JSON.toJSONString(t));
        request.setRequest(encryptParam(JSON.toJSONString(str)));
        log.info("加密后报文：{},URL：{}", JSON.toJSON(request), url);
        // 发送请求
        String res = RestHttpUtil.doPost(url, request);
        log.info("返回报文：{}", res);
        // 解密数据
        Response<String> response = JSON.parseObject(res, Response.class);
        if (null != response.getResponse()) {
            response.setResponse(decryptResponse(response.getResponse()));
            log.info("解密报文：{},", response.getResponse());
        }
        return response;
    }

    /**
     * 不加密对接标签平台统一http远程调用
     *
     * @param t 请求头数据
     * @param url TSG接口
     * @param <T> 泛型
     * @return 响应结果
     */
    public <T> Map<String, String> doPostNoEncryption(T t, String url) {
        // 发送请求
        String res = RestHttpUtil.doPost(url, t);
        log.info("返回报文：{}", res);
        return JSON.parseObject(res, new TypeReference<Map<String, String>>() {});
    }

    /**
     * 生成head
     *
     * @return
     */
    private <T> HeadBean getHeadBean(T t) {
        HeadBean head = new HeadBean();
        head.setSecretId(secretId);
        head.setRequestRefId("FOAREQ_" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
        // 身份签名串生成
        try {
            String str = SignUtils.getStr(t, head.getSecretId(), head.getRequestRefId());
            log.info("sign明文：{}", str);
            String sign = HMACSHA1.hmacSHA1Encrypt(str, secretKey);
            head.setSignature(sign);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return head;
    }

    private String encryptParam(String request) {
        try {
            return ThreeDES.encrypt(request, secretKey, "PKCS5", null, "ECB");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String decryptResponse(String response) {
        try {
            return ThreeDES.decrypt(response, secretKey, "PKCS5", null, "ECB");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        RestHttpPost restHttpPost = new RestHttpPost();
        // TaskSend taskSend = new TaskSend();
        // taskSend.setCustomerId("123").setPlanName("456").setAppreoverName("789");

        UserRelation taskSend = new UserRelation();
        List<String> list = new ArrayList<>();
        list.add("BQ20220419171033");
        taskSend.setVal("88884ac8-b90d-4b32-8692-3866252bf235");
        taskSend.setDataType("3");
        taskSend.setCustomerIds(list);
        Request<String> request = new Request<>();
        request.setHead(restHttpPost.getHeadBean(taskSend));
        RequestBean<String> str = new RequestBean<>();
        str.setParam(JSON.toJSONString(taskSend));
        System.out.println("request明文：" + JSON.toJSONString(str));
        request.setRequest(restHttpPost.encryptParam(JSON.toJSONString(str)));
        System.out.println("加密后：" + request);
        Object o = JSON.toJSON(request);
        System.out.println("请求json：" + o);
        String s = restHttpPost.decryptResponse(request.getRequest());
        request.setRequest(s);
        System.out.println("解密后：" + request);
    }

}
